<template>
  <div class="parent-div">
    <el-card>
      <el-form :model="pwdForm">
        <el-form-item label="新的密码:">
          <el-input v-model="pwdForm.pwd" placeholder="请输入新的密码" show-password/>
        </el-form-item>
        <el-form-item label="确认密码:">
          <el-input v-model="pwdForm.pwd_confirm" placeholder="请重新输入新的密码" show-password/>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="changePwd">修改密码</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import axios from "axios";
import {onMounted, reactive} from "vue";
import {useRouter} from 'vue-router'
import {ElMessage} from "element-plus";

const router = useRouter()
const pwdForm = reactive({
  pwd: '',
  pwd_confirm: '',
})

const errors = () => {
  ElMessage.error('两次密码不一致')
}

onMounted(() => {
  if(localStorage.username === undefined || localStorage.stuID === undefined) {
    router.push({path: '/'})
  }
})

const changePwd = () => {
  if(pwdForm.pwd !== pwdForm.pwd_confirm) {
    errors()
    return
  }
  let data_ = new FormData()
  data_.append('pwd', pwdForm.pwd)
  axios.post('/api/changePwd', data_)
      .then(res => {
        let result = res.data;
        localStorage.username = result['name']
        localStorage.stuID = result['id']
        router.go(0)
      })
}



</script>

<style scoped>
.parent-div {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
el-card {
  margin-left: auto;
  margin-right: auto;
}
</style>